<template>
  <div class="erp-dashboard-container">
    <el-row :gutter="20">
      <!-- 第一行 -->
      <el-col :lg="6" :md="12"  :sm="24" :xl="6" :xs="24">
        <el-card class="dashboard-card" shadow="never">
          <div slot="header">
            <span>总销售额 (本月)</span>
          </div>
          <div class="kpi-value">¥ {{ monthlySales.toLocaleString() }}</div>
        </el-card>
      </el-col>
      <el-col :lg="6" :md="12"   :sm="24" :xl="6" :xs="24">
        <el-card class="dashboard-card" shadow="never">
          <div slot="header">
            <span>总采购额 (本月)</span>
          </div>
          <div class="kpi-value">¥ {{ monthlyPurchases.toLocaleString() }}</div>
        </el-card>
      </el-col>
      <el-col :lg="6" :md="12"  :sm="24" :xl="6" :xs="24">
        <el-card class="dashboard-card" shadow="never">
          <div slot="header">
            <span>活跃供应商</span>
          </div>
          <div class="kpi-value">{{ activeSuppliers }}</div>
        </el-card>
      </el-col>
      <el-col :lg="6" :md="12"  :sm="24" :xl="6" :xs="24">
        <el-card class="dashboard-card" shadow="never">
          <div slot="header">
            <span>待处理订单</span>
            <el-button
              size="mini"
              style="float: right; margin-top: -5px;"
              type="primary"
              @click="goToOrderManagement">
              去处理
            </el-button>
          </div>
          <div class="kpi-value">{{ pendingOrders }}</div>
        </el-card>
      </el-col>

      <!-- 新增预测卡片 -->
      <el-col :lg="6" :md="12"  :sm="24" :xl="6" :xs="24">
        <el-card class="dashboard-card prediction-card" shadow="never">
          <div slot="header">
            <span>预测销售额 (下月)</span>
            <el-tooltip class="item" content="基于历史数据和季节性趋势的智能预测" effect="dark" placement="top">
              <i class="el-icon-question" style="margin-left: 5px;"></i>
            </el-tooltip>
          </div>
          <div class="kpi-value">¥ {{ predictedSales.toLocaleString() }}</div>
          <div class="prediction-trend">
            <span :class="salesTrend > 0 ? 'trend-up' : 'trend-down'">
              <i :class="salesTrend > 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
              {{ Math.abs(salesTrend).toFixed(1) }}%
            </span>
            <span class="trend-label">较本月</span>
          </div>
        </el-card>
      </el-col>

      <!-- 第二行 - 图表 -->
      <el-col :span="24">
        <el-card class="dashboard-chart-card" shadow="never">
          <div slot="header">
            <span>月度销售趋势</span>
            <!-- <el-switch
              v-model="showPrediction"
              active-text="显示预测"
              inactive-text="隐藏预测"
              style="float: right; margin-top: -5px;"
              @change="updateSalesTrendChart"
            /> -->
          </div>
          <div ref="salesTrendChart" style="height: 300px;"></div>
        </el-card>
      </el-col>

      <!-- 第三行 - 图表 -->
      <el-col :lg="12" :md="12"  :sm="24" :xl="12" :xs="24">
        <el-card class="dashboard-chart-card" shadow="never">
          <div slot="header">
            <span>采购订单状态分布</span>
          </div>
          <div ref="poStatusChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      <el-col :lg="12" :md="12"  :sm="24" :xl="12" :xs="24">
        <el-card class="dashboard-chart-card" shadow="never">
          <div slot="header">
            <span>热销商品Top5</span>
          </div>
          <div ref="topProductsChart" style="height: 300px;"></div>
        </el-card>
      </el-col>

      <!-- 第四行 - 图表 -->
      <el-col :lg="8" :md="8"  :sm="24" :xl="8" :xs="24">
        <el-card class="dashboard-chart-card" shadow="never">
          <div slot="header">
            <span>仓库使用率</span>
          </div>
          <div ref="warehouseAUsageChart" style="height: 250px;"></div>
        </el-card>
      </el-col>
      <el-col :lg="8" :md="8"  :sm="24" :xl="8" :xs="24">
        <el-card class="dashboard-chart-card" shadow="never">
          <div slot="header">
            <span>库存周转率</span>
          </div>
          <div ref="inventoryTurnoverChart" style="height: 250px;"></div>
        </el-card>
      </el-col>
      <el-col :lg="8" :md="8"  :sm="24" :xl="8" :xs="24">
        <el-card class="dashboard-chart-card" shadow="never">
          <div slot="header">
            <span>部门人数分布</span>
          </div>
          <div ref="employeeDepartmentChart" style="height: 250px;"></div>
        </el-card>
      </el-col>

      <!-- 新增智能人力资源优化卡片 -->
      <el-col :span="24">
        <el-card class="dashboard-chart-card" shadow="never">
          <div slot="header">
            <span>智能人力资源优化建议</span>
            <el-button
            size="mini"
            style="float: right; margin-top: -5px;"
              type="primary"
              @click="generateHROptimization"
            >
              重新生成建议
            </el-button>
          </div>
          <div class="hr-optimization-container">
            <div class="hr-optimization-summary">
              <h3>基于销售预测的人力资源优化方案</h3>
              <p>{{ hrOptimizationSummary }}</p>
            </div>
            <div class="hr-optimization-details">
              <div ref="hrOptimizationChart" style="height: 300px; width: 100%;"></div>
              <div class="hr-optimization-recommendations">
                <h4>具体建议</h4>
                <el-timeline>
                  <el-timeline-item
                    v-for="(recommendation, index) in hrRecommendations"
                    :key="index"
                    :color="recommendation.color"
                    :timestamp="recommendation.timestamp"
                    :type="recommendation.type"
                  >
                    {{ recommendation.content }}
                  </el-timeline-item>
                </el-timeline>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts' // 引入 ECharts

export default {
  name: 'ErpDashboard', // 重命名组件
  data() {
    return {
      monthlySales: 2568432,
      monthlyPurchases: 0,
      activeSuppliers: 0,
      pendingOrders: 0,

      // 新增预测相关数据
      predictedSales: 0,
      salesTrend: 0,
      showPrediction: true,
      historicalSalesData: [],
      predictedSalesData: [],

      // 人力资源优化相关数据
      hrOptimizationSummary: '',
      hrRecommendations: [],
      currentDepartmentData: [],
      optimizedDepartmentData: [],

      // ECharts 实例
      salesTrendChartInstance: null,
      poStatusChartInstance: null,
      topProductsChartInstance: null,
      warehouseAUsageChartInstance: null,
      inventoryTurnoverChartInstance: null,
      employeeDepartmentChartInstance: null,
      hrOptimizationChartInstance: null,
    }
  },
  created() {
    this.loadPendingOrdersCount();
  },
  mounted() { // 使用 mounted 确保 DOM 准备就绪
    this.generateKpiData()
    this.generateHistoricalData()
    this.predictSales()
    this.generateHROptimization()

    this.initSalesTrendChart()
    this.initPoStatusChart()
    this.initTopProductsChart()
    this.initWarehouseAUsageChart()
    this.initInventoryTurnoverChart()
    this.initEmployeeDepartmentChart()
    this.initHROptimizationChart()

    // 监听窗口大小变化，以便调整图表大小
    window.addEventListener('resize', this.handleResizeCharts)
  },

  beforeDestroy() {
    // 销毁 ECharts 实例并移除事件监听器
    this.disposeCharts()
    window.removeEventListener('resize', this.handleResizeCharts)
  },
  methods: {
    generateKpiData() {
      // this.monthlySales = Math.floor(Math.random() * 500000) + 100000 // 100k - 600k
      this.monthlyPurchases = Math.floor(Math.random() * 300000) + 50000 // 50k - 350k
      this.activeSuppliers = Math.floor(Math.random() * 10) + 0 // 2 - 20
    },

    // 生成历史销售数据
    generateHistoricalData() {
      // 生成过去12个月的销售数据，包含季节性趋势
      const baseValue = 50; // 基础销售额（万元）
      const seasonalFactors = [0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.2, 1.1, 1.0, 0.9, 1.1, 1.5]; // 季节性因子
      const trend = 0.05; // 整体上升趋势

      this.historicalSalesData = [];

      for (let i = 0; i < 6; i++) {
        // 添加随机波动
        const randomFactor = 0.9 + Math.random() * 0.2; // 0.9-1.1的随机因子
        // 计算当月销售额 = 基础值 * (1 + 趋势 * 月份) * 季节因子 * 随机因子
        const monthValue = Math.round(baseValue * (1 + trend * i) * seasonalFactors[i] * randomFactor);
        this.historicalSalesData.push(monthValue);
      }
    },

    // 预测销售额
    predictSales() {
      if (this.historicalSalesData.length === 0) {
        this.generateHistoricalData();
      }

      // 简单的时间序列预测算法
      // 1. 计算历史数据的趋势
      const n = this.historicalSalesData.length;
      let sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0;

      for (let i = 0; i < n; i++) {
        sumX += i;
        sumY += this.historicalSalesData[i];
        sumXY += i * this.historicalSalesData[i];
        sumX2 += i * i;
      }

      // 线性回归: y = a + bx
      const b = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
      const a = (sumY - b * sumX) / n;

      // 预测未来3个月
      this.predictedSalesData = [];
      for (let i = 0; i < 3; i++) {
        const month = n + i;
        // 基础预测值
        let predictedValue = a + b * month;

        // 考虑季节性因素
        const seasonalIndex = (n + i) % 12;
        const seasonalFactor = seasonalFactors[seasonalIndex];

        // 应用季节性因子
        predictedValue *= seasonalFactor;

        // 添加一些随机波动，使预测更自然
        const randomFactor = 0.95 + Math.random() * 0.1; // 0.95-1.05的随机因子
        predictedValue *= randomFactor;

        this.predictedSalesData.push(Math.round(predictedValue));
      }

      // 将预测的销售额（万元）转换为实际金额
      this.predictedSales = this.predictedSalesData[0] * 10000;

      // 计算环比增长率
      const currentSales = this.historicalSalesData[this.historicalSalesData.length - 1];
      this.salesTrend = ((this.predictedSalesData[0] - currentSales) / currentSales) * 100;
    },

    // 生成人力资源优化建议
    generateHROptimization() {
      // 获取当前部门人数分布
      this.getCurrentDepartmentData();

      // 基于销售预测计算最优人力分配
      this.calculateOptimalStaffing();

      // 生成优化建议
      this.generateHRRecommendations();

      // 更新人力资源优化图表
      this.$nextTick(() => {
        this.updateHROptimizationChart();
      });
    },

    // 获取当前部门人数分布
    getCurrentDepartmentData() {
      // 从部门分布图表中获取数据
      if (this.employeeDepartmentChartInstance) {
        const option = this.employeeDepartmentChartInstance.getOption();
        const seriesData = option.series[0].data;

        this.currentDepartmentData = seriesData.map(item => ({
          name: item.name,
          value: item.value
        }));
      } else {
        // 如果图表实例不存在，生成模拟数据
        this.currentDepartmentData = [
          { name: '销售部', value: Math.floor(Math.random() * 30) + 10 },
          { name: '市场部', value: Math.floor(Math.random() * 20) + 5 },
          { name: '技术部', value: Math.floor(Math.random() * 50) + 15 },
          { name: '人事部', value: Math.floor(Math.random() * 15) + 5 },
          { name: '财务部', value: Math.floor(Math.random() * 10) + 3 }
        ];
      }
    },

    // 计算最优人力分配
    calculateOptimalStaffing() {
      // 基于销售预测的增长率调整人力资源
      const salesGrowthRate = this.salesTrend / 100;

      // 智能算法：根据销售增长预测调整各部门人数
      this.optimizedDepartmentData = this.currentDepartmentData.map(dept => {
        let adjustmentFactor = 0;

        // 根据部门不同，设置不同的调整系数
        switch (dept.name) {
          case '销售部':
            // 销售部人数与销售增长直接相关
            adjustmentFactor = salesGrowthRate * 1.2;
            break;
          case '市场部':
            // 市场部人数与销售增长相关，但滞后性较强
            adjustmentFactor = salesGrowthRate * 0.8;
            break;
          case '技术部':
            // 技术部人数与销售关系较弱，但需要保持基本稳定
            adjustmentFactor = salesGrowthRate * 0.3;
            break;
          case '人事部':
            // 人事部随公司整体规模变化而变化
            adjustmentFactor = salesGrowthRate * 0.5;
            break;
          case '财务部':
            // 财务部变化较小
            adjustmentFactor = salesGrowthRate * 0.2;
            break;
          default:
            adjustmentFactor = salesGrowthRate * 0.5;
        }

        // 计算调整后的人数
        let newValue = Math.round(dept.value * (1 + adjustmentFactor));

        // 确保每个部门至少有最低人数
        const minStaff = {
          '销售部': 5,
          '市场部': 3,
          '技术部': 8,
          '人事部': 2,
          '财务部': 2
        };

        newValue = Math.max(newValue, minStaff[dept.name] || 2);

        return {
          name: dept.name,
          value: newValue,
          originalValue: dept.value,
          change: newValue - dept.value
        };
      });
    },

    // 生成人力资源优化建议
    generateHRRecommendations() {
      // 根据优化结果生成具体建议
      const totalCurrentStaff = this.currentDepartmentData.reduce((sum, dept) => sum + dept.value, 0);
      const totalOptimizedStaff = this.optimizedDepartmentData.reduce((sum, dept) => sum + dept.value, 0);
      const staffingChange = totalOptimizedStaff - totalCurrentStaff;

      // 生成总结
      if (staffingChange > 0) {
        this.hrOptimizationSummary = `基于下月销售额预测增长${Math.abs(this.salesTrend).toFixed(1)}%，建议总人力扩充${staffingChange}人，重点加强销售和市场团队，以支持业务增长。`;
      } else if (staffingChange < 0) {
        this.hrOptimizationSummary = `基于下月销售额预测下降${Math.abs(this.salesTrend).toFixed(1)}%，建议优化人力结构，总人数调整${staffingChange}人，提高人均效能。`;
      } else {
        this.hrOptimizationSummary = `基于下月销售预测，建议保持现有人力规模，但可优化内部人员结构，提高关键部门效能。`;
      }

      // 生成具体建议
      this.hrRecommendations = [];

      // 添加部门调整建议
      this.optimizedDepartmentData.forEach(dept => {
        if (dept.change !== 0) {
          const recommendation = {
            content: '',
            type: dept.change > 0 ? 'primary' : 'warning',
            color: dept.change > 0 ? '#409EFF' : '#E6A23C',
            timestamp: '下月实施'
          };

          if (dept.change > 0) {
            recommendation.content = `${dept.name}：建议增加${dept.change}人，以应对预期的业务增长`;
          } else {
            recommendation.content = `${dept.name}：建议精简${Math.abs(dept.change)}人，提高部门效能`;
          }

          this.hrRecommendations.push(recommendation);
        }
      });

      // 添加一些智能建议
      if (this.salesTrend > 10) {
        // 销售增长较大时的建议
        this.hrRecommendations.push({
          content: '建议提前启动销售人员招聘流程，确保能及时满足业务增长需求',
          type: 'success',
          color: '#67C23A',
          timestamp: '立即执行'
        });
      } else if (this.salesTrend < -10) {
        // 销售下降较大时的建议
        this.hrRecommendations.push({
          content: '建议暂停非必要岗位招聘，通过内部调岗满足关键岗位需求',
          type: 'danger',
          color: '#F56C6C',
          timestamp: '立即执行'
        });
      }

      // 添加培训建议
      this.hrRecommendations.push({
        content: '建议针对销售团队开展产品知识培训，提高单人销售效能',
        type: 'info',
        color: '#909399',
        timestamp: '两周内'
      });
    },

    initSalesTrendChart() {
      const chartDom = this.$refs.salesTrendChart
      if (!chartDom) return
      this.salesTrendChartInstance = echarts.init(chartDom)

      // 使用生成的历史数据
      if (this.historicalSalesData.length === 0) {
        this.generateHistoricalData();
      }

      const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月'];

      const option = {
        tooltip: { trigger: 'axis' },
        legend: {
          data: ['历史销售额', '预测销售额']
        },
        xAxis: {
          type: 'category',
          data: months.slice(0, this.historicalSalesData.length + this.predictedSalesData.length),
          axisPointer: {
            type: 'shadow'
          }
        },
        yAxis: { type: 'value', name: '销售额 (万元)' },
        series: [
          {
            name: '历史销售额',
            type: 'line',
            smooth: true,
            data: this.historicalSalesData,
            itemStyle: {
              color: '#409EFF'
            }
          },
          {
            name: '预测销售额',
            type: 'line',
            smooth: true,
            data: Array(this.historicalSalesData.length).fill('-').concat(this.predictedSalesData),
            lineStyle: {
              type: 'dashed',
              color: '#F56C6C'
            },
            itemStyle: {
              color: '#F56C6C'
            }
          }
        ],
        grid: { top: '15%', left: '3%', right: '4%', bottom: '3%', containLabel: true }
      }
      this.salesTrendChartInstance.setOption(option)
    },

    // 更新销售趋势图表，显示或隐藏预测数据
    updateSalesTrendChart() {
      if (!this.salesTrendChartInstance) return;

      const option = this.salesTrendChartInstance.getOption();

      if (this.showPrediction) {
        // 显示预测数据
        option.legend.data = ['历史销售额', '预测销售额'];
        option.series = [
          {
            name: '历史销售额',
            type: 'line',
            smooth: true,
            data: this.historicalSalesData,
            itemStyle: {
              color: '#409EFF'
            }
          },
          {
            name: '预测销售额',
            type: 'line',
            smooth: true,
            data: Array(this.historicalSalesData.length).fill('-').concat(this.predictedSalesData),
            lineStyle: {
              type: 'dashed',
              color: '#F56C6C'
            },
            itemStyle: {
              color: '#F56C6C'
            }
          }
        ];
      } else {
        // 隐藏预测数据
        option.legend.data = ['历史销售额'];
        option.series = [
          {
            name: '历史销售额',
            type: 'line',
            smooth: true,
            data: this.historicalSalesData,
            itemStyle: {
              color: '#409EFF'
            }
          }
        ];
      }

      this.salesTrendChartInstance.setOption(option);
    },

    // 初始化人力资源优化图表
    initHROptimizationChart() {
      const chartDom = this.$refs.hrOptimizationChart;
      if (!chartDom) return;

      this.hrOptimizationChartInstance = echarts.init(chartDom);
      this.updateHROptimizationChart();
    },

    // 更新人力资源优化图表
    updateHROptimizationChart() {
      if (!this.hrOptimizationChartInstance) return;

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['当前人数', '建议人数']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          boundaryGap: [0, 0.01]
        },
        yAxis: {
          type: 'category',
          data: this.optimizedDepartmentData.map(item => item.name)
        },
        series: [
          {
            name: '当前人数',
            type: 'bar',
            data: this.optimizedDepartmentData.map(item => item.originalValue)
          },
          {
            name: '建议人数',
            type: 'bar',
            data: this.optimizedDepartmentData.map(item => item.value)
          }
        ]
      };

      this.hrOptimizationChartInstance.setOption(option);
    },

    initPoStatusChart() {
      const chartDom = this.$refs.poStatusChart
      if (!chartDom) return
      this.poStatusChartInstance = echarts.init(chartDom)
      const option = {
        tooltip: { trigger: 'item' },
        legend: { top: '5%', left: 'center' },
        series: [
          {
            name: '订单状态',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
            label: { show: false, position: 'center' },
            emphasis: { label: { show: true, fontSize: '20', fontWeight: 'bold' } },
            labelLine: { show: false },
            data: [
              { value: Math.floor(Math.random() * 100) + 20, name: '待审批' },
              { value: Math.floor(Math.random() * 100) + 50, name: '已批准' },
              { value: Math.floor(Math.random() * 100) + 30, name: '采购中' },
              { value: Math.floor(Math.random() * 100) + 10, name: '已完成' },
              { value: Math.floor(Math.random() * 20), name: '已取消' },
            ],
          },
        ],
      }
      this.poStatusChartInstance.setOption(option)
    },

    initTopProductsChart() {
      const chartDom = this.$refs.topProductsChart
      if (!chartDom) return
      this.topProductsChartInstance = echarts.init(chartDom)
      const products = ['商品A', '商品B', '商品C', '商品D', '商品E'].sort(() => 0.5 - Math.random())
      const option = {
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        xAxis: {
          type: 'category',
          data: products,
        },
        yAxis: { type: 'value', name: '销量' },
        series: [
          {
            name: '销量',
            type: 'bar',
            data: Array.from({ length: 5 }, () => Math.floor(Math.random() * 500) + 50),
            barWidth: '40%',
          },
        ],
        grid: { top: '15%', left: '3%', right: '4%', bottom: '3%', containLabel: true }
      }
      this.topProductsChartInstance.setOption(option)
    },

    initWarehouseAUsageChart() {
      const chartDom = this.$refs.warehouseAUsageChart
      if (!chartDom) return
      this.warehouseAUsageChartInstance = echarts.init(chartDom)
      const usage = Math.floor(Math.random() * 80) + 20 // 20-100%
      const option = {
        tooltip: { formatter: '{a} <br/>{b} : {c}%' },
        series: [
          {
            name: '仓库使用率',
            type: 'gauge',
            detail: { formatter: '{value}%' },
            data: [{ value: usage, name: '仓库' }],
            axisLine: {
              lineStyle: {
                width: 15,
                color: [
                  [0.6, '#67C23A'], // 绿色
                  [0.8, '#E6A23C'], // 黄色
                  [1, '#F56C6C'],   // 红色
                ],
              },
            },
            progress: { show: true, width: 15 },
          },
        ],
      }
      this.warehouseAUsageChartInstance.setOption(option)
    },

    initInventoryTurnoverChart() {
      const chartDom = this.$refs.inventoryTurnoverChart;
      if (!chartDom) return;
      this.inventoryTurnoverChartInstance = echarts.init(chartDom);
      const turnoverRate = (Math.random() * 10 + 2).toFixed(1); // 2.0 - 12.0
      const option = {
        tooltip: { formatter: '{a} <br/>{b} : {c}' },
        series: [
          {
            name: '库存周转率',
            type: 'gauge',
            min: 0,
            max: 15,
            splitNumber: 5,
            detail: { formatter: '{value}' },
            data: [{ value: parseFloat(turnoverRate), name: '周转次数' }],
            axisLine: {
              lineStyle: {
                width: 15,
                color: [
                  [0.3, '#F56C6C'],
                  [0.7, '#E6A23C'],
                  [1, '#67C23A'],
                ],
              },
            },
            progress: { show: true, width: 15 },
          },
        ],
      };
      this.inventoryTurnoverChartInstance.setOption(option);
    },

    initEmployeeDepartmentChart() {
      const chartDom = this.$refs.employeeDepartmentChart;
      if (!chartDom) return;
      this.employeeDepartmentChartInstance = echarts.init(chartDom);
      const option = {
        tooltip: { trigger: 'item' },
        legend: {
          orient: 'vertical',
          left: 'left',
          top: 'center'
        },
        series: [
          {
            name: '部门分布',
            type: 'pie',
            radius: '70%',
            center: ['65%', '50%'], // 调整饼图位置以容纳图例
            data: [
              { value: Math.floor(Math.random() * 30) + 10, name: '销售部' },
              { value: Math.floor(Math.random() * 20) + 5, name: '市场部' },
              { value: Math.floor(Math.random() * 50) + 15, name: '技术部' },
              { value: Math.floor(Math.random() * 15) + 5, name: '人事部' },
              { value: Math.floor(Math.random() * 10) + 3, name: '财务部' },
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      };
      this.employeeDepartmentChartInstance.setOption(option);
    },

    handleResizeCharts() {
      // 调整所有图表的大小
      if (this.salesTrendChartInstance) this.salesTrendChartInstance.resize()
      if (this.poStatusChartInstance) this.poStatusChartInstance.resize()
      if (this.topProductsChartInstance) this.topProductsChartInstance.resize()
      if (this.warehouseAUsageChartInstance) this.warehouseAUsageChartInstance.resize()
      if (this.inventoryTurnoverChartInstance) this.inventoryTurnoverChartInstance.resize()
      if (this.employeeDepartmentChartInstance) this.employeeDepartmentChartInstance.resize()
      if (this.hrOptimizationChartInstance) this.hrOptimizationChartInstance.resize()
    },

    disposeCharts() {
      // 销毁 ECharts 实例
      if (this.salesTrendChartInstance) this.salesTrendChartInstance.dispose()
      if (this.poStatusChartInstance) this.poStatusChartInstance.dispose()
      if (this.topProductsChartInstance) this.topProductsChartInstance.dispose()
      if (this.warehouseAUsageChartInstance) this.warehouseAUsageChartInstance.dispose()
      if (this.inventoryTurnoverChartInstance) this.inventoryTurnoverChartInstance.dispose()
      if (this.employeeDepartmentChartInstance) this.employeeDepartmentChartInstance.dispose()
      if (this.hrOptimizationChartInstance) this.hrOptimizationChartInstance.dispose()
    },

    // 从localStorage读取待支付订单数量
    loadPendingOrdersCount() {
      try {
        const count = localStorage.getItem('pendingOrdersCount');
        this.pendingOrders = count ? parseInt(count) : 0;
      } catch (error) {
        console.error('读取待支付订单数量失败:', error);
        this.pendingOrders = 0;
      }
    },

    // 跳转到账单管理页面
    goToOrderManagement() {
      this.$router.push('/vab/menuManagement');
    },
  },
}

// 季节性因子数组（全局变量）
const seasonalFactors = [0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.2, 1.1, 1.0, 0.9, 1.1, 1.5];
</script>

<style lang="scss" scoped>
.erp-dashboard-container {
  padding: 20px;
  background-color: #f0f2f5; // 背景色，可以根据您的主题调整
}

.dashboard-card {
  margin-bottom: 20px;
  .kpi-value {
    font-size: 24px;
    font-weight: bold;
    color: #303133;
    padding-top: 10px;
  }
}

.dashboard-chart-card {
  margin-bottom: 20px;
}

// 确保el-card的header和body有合适的padding
::v-deep .el-card__header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  box-sizing: border-box;
  font-size: 16px;
  font-weight: 500;
}

::v-deep .el-card__body {
  padding: 20px;
}
</style>
